package com.yzt.plugin_widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.TextUtils;
import android.util.AttributeSet;

/**
 * author : bob
 * date   : 2022/12/2
 * desc   :
 */
public class GiftNumTextView extends androidx.appcompat.widget.AppCompatTextView {

    private LinearGradient mLinearGradient;

    private Paint mPaint;

    private int mViewWidth = 0;

    private int mViewHeight = 0;

    private int mLastViewWidth = 0;

    private final Rect mTextBound = new Rect();

    public GiftNumTextView(Context context) {
        super(context);
    }

    public GiftNumTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        text = text + " ";
        super.setText(text, type);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {

        mPaint = getPaint();
        String mTipText = getText().toString();
        if (TextUtils.isEmpty(mTipText)) {
            return;
        }
        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);

        if (mLastViewWidth == 0) {
            mViewWidth = getMeasuredWidth();
            mLastViewWidth = mViewWidth + mTextBound.width() / mTipText.length() / 2;
        }
        mViewHeight = getMeasuredHeight();
        mLinearGradient = new LinearGradient(0, 0, 0, mViewHeight,
                new int[]{0xFFFAD961, 0xFFF76B1C},
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);

        mPaint.setStrokeWidth(3);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setFakeBoldText(true);
        canvas.drawText(mTipText, 0, mViewHeight / 2 + mTextBound.height() / 2, mPaint);


        mPaint.setStrokeWidth(0);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setFakeBoldText(false);
        mLinearGradient = new LinearGradient(0, 0, 0, mViewHeight,
                new int[]{0xFFFFFBB0, 0xFFFFBD0C},
                null, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        canvas.drawText(mTipText, 0, mViewHeight / 2 + mTextBound.height() / 2, mPaint);

        requestLayout();
    }
}
